import React, {Component} from 'react'
import {View, Text, TouchableOpacity, Image, Dimensions, Modal} from 'react-native'
import Spinner from 'react-native-spinkit'
import Icon from 'react-native-vector-icons/Ionicons'
import Recording from 'react-native-recording'
import * as Progress from 'react-native-progress'
import {connect} from 'react-redux'
import filterSentenceForAnalysis, {checkName, getNormalPhone} from '../../helpers/contentForIbm'
import {youdaoTranslateApi,saveExerciseData} from '../../config/api'
import {fsReadPath} from '../../helpers/fsHelper'
import styles, { BLUE } from '../../config/styles'
var Sound = require('react-native-sound')
Sound.setCategory('Playback')
const screenWidth = Dimensions.get('window').width


class SentenceLabel extends Component {
    static defaultProps = {
        sentence: {},
        isActive: false,
        isPlaying: false,
        isRecording: false,
        isPlaybacking: false,
        onPress: (() => {}),
        setPlayState: (() => {}),
        setRecordingState: (() => {}),
        setPlaybackState: (() => {})
    }

    state = {
        voiceLength: 1,
        voiceProgress: 0,
        ws: {},
        playbackUrl: null, //录音完成后的回放链接,
        score: null, //分数
        ibmSentences: [], //录音后IBM返回的结果，有结果的情况下显示的内容会发生变化
        youdaoResult: null, //点击一个单词后，有道返回的结果对象
        modalVisible: false,//点击某个单词之后弹出有道的翻译结果
        wsLocked: false //一次ws链接后，不能连续链接
    }

   
    componentDidMount () {
        //this.client = new wClient()
    }

    componentWillUnmount () {
        if (this.loop_get_time != undefined) {clearInterval(this.loop_get_time)}
        if (this.voice != undefined) {this.voice.release()}
        if (this.playback_voice != undefined) {this.playback_voice.release()}
        if (this.state.ws != null && this.state.ws.readyState === 1) {this.state.ws.close()}
        if (this.listener != undefined) {this.listener.remove()}
    }

    componentDidMount () {
        // if (this.props.isActive) {
        //     this.listener = Recording.addRecordingEventListener((data) => {
        //         if (this.state.ws != null && this.state.ws.readyState === 1) {
        //             this.state.ws.send(JSON.stringify({
        //                 stream_type: 'array',
        //                 stream: data,
        //                 status: 'process'
        //             }))
        //         }
        //     })
        // }
       
    }

    componentWillReceiveProps(nextProps) {
        const recording = nextProps.recording
        if (nextProps.isActive == false) {
            if (this.voice != undefined) {
                this.voice.release()
                this.voice = undefined
            }

            if (this.playback_voice != undefined) {
                this.playback_voice.release()
                this.playback_voice = undefined
            }
           
        } 
    }

    //判断音频是否加载完成
    soundLoaded = () => {
        if (this.voice == undefined) return false
        return this.voice.isLoaded()
    }

    //判断回放的音频是否加载完成
    playbackSoundLoaded = () => {
        if (this.playback_voice == undefined) return false
        return this.playback_voice.isLoaded()
    }

     //播放按钮的icon模板
    playerStatusIcon = () => {
        const soundLoaded = this.soundLoaded()
        const {isPlaying, isRecording, isPlaybacking} = this.props
        if (isPlaying) {
            if (soundLoaded) {
                return (
                    <View style={[styles.icon_container, {backgroundColor: '#00FF00'}]}>
                        <View style={styles.icon_inner_container}>
                            <Icon name={'ios-pause'} size={40} color={'white'} />
                        </View>
                    </View>    
                )
            } else {
                return ( <View style={[styles.icon_container]}>
                            <View style={styles.icon_inner_container}>
                                <Spinner type={'Bounce'} color={'white'} />
                            </View>
                        </View>)
            }
        } else {
            const _backgroundColor = (isRecording || isPlaybacking) ? 'gray' : BLUE
            return (
                <View style={[styles.icon_container, {backgroundColor: _backgroundColor}]}>
                    <View style={styles.icon_inner_container}>
                        <Icon name={'ios-play'} size={40} color={'white'} />
                    </View>
                </View>  
            )
        }
    }

    //录音按钮的icon模板
    recorderStatusIcon = () => {
        const {isRecording, isPlaying, isPlaybacking} = this.props
        if (isRecording) {
            return(
                <View style={[styles.icon_container, styles.large_icon, {backgroundColor: '#00FF00'}]}>
                    <View style={styles.icon_inner_container}>
                        <Spinner type={'Wave'} color={'white'} />
                    </View>
                </View>   
            )
        } else {
            const _backgroundColor = (isPlaying || isPlaybacking) ? 'gray' : BLUE
            return(
                <View style={[styles.icon_container, styles.large_icon, {backgroundColor: _backgroundColor}]}>
                    <View style={styles.icon_inner_container}>
                        <Icon name={'ios-mic-outline'} size={40} color={'white'} />
                    </View>
                </View>   
            )
        }
    }

    //回放按钮的icon模板
    playbackStatusIcon = () => {
        const playbackSoundLoaded = this.playbackSoundLoaded()
        const {isPlaybacking, isPlaying, isRecording} = this.props
        if (isPlaybacking) {
            return(
                <View style={[styles.icon_container, {backgroundColor: '#00FF00'}]}>
                    <View style={styles.icon_inner_container}>
                        <Spinner type={'ThreeBounce'} color={'white'} />
                    </View>
                </View>  
            ) 
        } else {
            const _backgroundColor = (this.state.playbackUrl == null || isPlaying || isRecording) ? 'gray' : BLUE
            return(
                <View style={[styles.icon_container, {backgroundColor: _backgroundColor}]}>
                    <View style={styles.icon_inner_container}>
                        <Icon name={'ios-podium-outline'} size={40} color={'white'} />
                    </View>
                </View>      
            )
        }
    }

    //分数显示
    scoreTemplate = () => {
        if (this.state.score == null) {
            return null
        } else {
            return (
                <View style={styles.score_template}>
                    <Text style={{color: 'white'}}>
                        {this.state.score}
                    </Text>
                </View>
            )
        }
    }

    //获取有道的翻译结果，顺便把当前点击的ibmSentence的音标也放在youdaoResult里面
    getYoudaoTranslate = (ibmSentence) => {
        let _word = checkName(ibmSentence.word)
        youdaoTranslateApi(_word).then((result) => {
            // console.log('result', result)
            this.setState({
                modalVisible: true,
                youdaoResult: {
                    word: _word,
                    phones: ibmSentence.phones,
                    youdaoSoundUrl: `http://dict.youdao.com/dictvoice?type=2&audio=${result.query}`,
                    youdaoTranslates: result.basic.explains
                }
            })
        })//.catch((err) => {console.log('err', err)})
    }

    //关闭modal
    closeModal = () => {
        this.setState({modalVisible: false})
    }   

    //获取单词颜色
    getWordColor = (score) => {
        const {score_weighting} = this.props.user.settings
        let color
                            
        if (score >= score_weighting.good) {
            color = 'blue'
        } else if (score >= score_weighting.poor && score < score_weighting.good) {
            color = 'red'
        } else {
            color = 'gray'
        }

        return color
    }

    //
    getPhonesTemplate = (raw_phones=[]) => {
        return (
            <View style={{flexDirection: 'row'}}>
                {raw_phones.map((rawPhone, index) => {
                    return(
                        <Text key={index} 
                            style={[
                                styles.youdaoFont, 
                                {
                                    color: this.getWordColor(rawPhone.pron_score),
                                }
                            ]}
                        >
                            {getNormalPhone(rawPhone.phone)}
                        </Text>
                    )
                })}
            </View>
        )
    }

    //有道的翻译模态框
    youdaoModalTemplate = () => {
        const {youdaoResult} = this.state
        if (youdaoResult == null) return null
        return (
            <Modal
                animationType={'slide'}
                visible={this.state.modalVisible}
                transparent={true}
                onRequestClose={() => {}}                
            >
                <TouchableOpacity
                    style={{flex: 1, marginBottom: 0, flexDirection: 'column-reverse'}}
                    onPress={() => {this.closeModal()}}
                >
                    <View style={{flex: 1}}>
                        <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)'}} />
                        <View style={{backgroundColor: '#00BBFF', padding: 15}}>
                            <Text style={{color: 'white', fontWeight: 'bold'}}>
                                这个单词的发音有待提高：标红严重错误/标绿一般错误/标蓝发音准确，请仔细纠正错误，多加练习。
                            </Text>
                        </View>
                        <View style={{backgroundColor: 'white'}}>
                            <View style={{flexDirection: 'row', padding: 10}}>
                                <Text style={[styles.youdaoFont, {paddingRight: 10}]}>
                                    {youdaoResult.word}
                                </Text>
                                <Text style={styles.youdaoFont}>[</Text>
                                {this.getPhonesTemplate(youdaoResult.phones)}
                                <Text style={styles.youdaoFont}>]</Text>
                                <TouchableOpacity
                                    style={{padding: 10}}
                                    onPress={() => {this.playYoudaoSound(youdaoResult.youdaoSoundUrl)}}
                                >
                                    <Icon name={'md-volume-up'} color={'orange'} size={30} />
                                </TouchableOpacity>
                            </View>
                            <View style={{padding: 10}}>
                                {
                                    youdaoResult.youdaoTranslates.map((t, index) => {
                                        return(
                                            <Text key={index}>{t}</Text>
                                        ) 
                                    })
                                }
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
            </Modal>
        )
    }
    

    //内容显示的模板
    sentenceTemplate = () => {
        const {sentence, user, isActive} = this.props
        const _color = isActive ? 'black' : 'grey'
        if (this.state.ibmSentences.length == 0) {
            return (
            <Text style={[styles.sentence_label_text, {flex: 1, color: _color}]}>
                {sentence.content}
            </Text>)
        } else {
            return(
                <View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
                    {
                        this.state.ibmSentences.map((ibmSentence, index) => {
                            let score = ibmSentence.score
                            return (
                                <TouchableOpacity 
                                    key={index} 
                                    onPress={() => {this.getYoudaoTranslate(ibmSentence)}}
                                >
                                    <Text style={[styles.sentence_label_text, {fontWeight: 'bold', color: this.getWordColor(score)}]}>
                                        {ibmSentence.word + " "}
                                    </Text>
                                </TouchableOpacity>
                               
                            )
                        })
                    }
                </View>
                
            )
          
        }
    }

    //选中状态的模板
    templateWithActive = (sentence) => {
        return (
            <View style={{flex: 1, backgroundColor: 'white',paddingTop:15}}>
                <View style={{flexDirection: 'row', flex: 1}}>
                    <View style={{margin: 5, flex: 1}}>
                        {this.sentenceTemplate()}
                    </View>
                    {this.scoreTemplate()}
                </View>
                <View style={{flexDirection: 'row', marginTop: 10}}>
                    <TouchableOpacity style={{flex: 1, alignItems: 'center'}} onPress={this.OnPlayButtonPress}>
                        {this.playerStatusIcon()}
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={{flex: 1, alignItems: 'center'}}
                        // onPressIn={this.onRecordingButtonPress}
                        // onPressOut={this.onRecordingButtonPress}
                        onPress={this.onRecordingButtonPress}
                        delayPressOut={100}
                        delayPressIn={0}
                    >
                       {this.recorderStatusIcon()}
                    </TouchableOpacity>
                    <TouchableOpacity style={{flex: 1, alignItems: 'center'}} onPress={this.onPlaybackButtonPress}>
                        {this.playbackStatusIcon()}
                    </TouchableOpacity>
                </View>
                <View style={{marginTop: 10}}>
                    <Progress.Bar progress={this.state.voiceProgress} width={null} borderWidth={0.1} height={3}/>
                </View>
            </View>
        )
    }

    //未选中状态的模板
    templateWithInActive = (sentence) => {
        return (
            <View style={[styles.sentence_label_container, {flex: 1,paddingTop:15,paddingLeft: 15}]}>
                <View style={{flexDirection: 'row', padding: 8}}>
                    {this.sentenceTemplate()}
                    {this.scoreTemplate()}
                </View>
               
            </View>
        )
    }

    //播放或停止
    OnPlayButtonPress = async () => {
        const {isPlaying, sentence, setPlayState, isRecording, isPlaybacking} = this.props
        if (isRecording || isPlaybacking) return
        const soundLoaded = this.soundLoaded()
        if (isPlaying) {
            this.voice.pause()
            setPlayState(false)
            clearInterval(this.loop_get_time)
        } else {
            setPlayState(true)
            if (soundLoaded) {
                this.play()
            } else {
                const _audio_url = await fsReadPath(sentence.audio_url)
                this.voice = new Sound(_audio_url, '', (error) => {
                    if (error) {
                        //console.log(error, 'error')
                        setPlayState(false)
                        return;
                    }
                    this.state.voiceLength = this.voice.getDuration()
                    this.play()
                });
            }
        }
    }

    //开始录音或停止录音
    onRecordingButtonPress = () => {
        const {sentence, onRecordingButtonPress} = this.props
        const {user} = this.props.user
        let timeStamp = new Date().getTime()

        onRecordingButtonPress(sentence, timeStamp).then(async ([e,seconds]) => {
            // 接收到了一个消息
            const _data = JSON.parse(e.data)
            if (_data.code == "200") {
                if (this.playback_voice != undefined) {
                    this.playback_voice.release(); 
                    this.playback_voice = null
                }
                this.afterRecord(_data.body,seconds,timeStamp)
                const _playbackUrl = await fsReadPath(`https://s3.cn-north-1.amazonaws.com.cn/oraltest/audios/${user.login_name}_${timeStamp}.wav`)
                this.setState({
                    playbackUrl: _playbackUrl
                })
            } else {
                alert('无法识别你的声音')
            }
        })
    }

    //回放或停止回放
    onPlaybackButtonPress = () => {
        const {isPlaying, isRecording, sentence, setPlaybackState, isPlaybacking} = this.props
        const url = this.state.playbackUrl
        const playbackSoundLoaded = this.playbackSoundLoaded()
        if (isPlaying || isRecording || url == null) return
        if (isPlaybacking) {
            this.playback_voice.pause()
            setPlaybackState(false)
            clearInterval(this.loop_get_time)
        } else {
            setPlaybackState(true)
            if (playbackSoundLoaded) {
                this.playback()
            } else {
                this.playback_voice = new Sound(url, '', (error) => {
                    if (error) {
                        //console.log(error, 'error')
                        setPlaybackState(false)
                        return;
                    }
                    this.state.voiceLength = this.playback_voice.getDuration()
                    this.playback()
                });
            }
           
        }
    }

    //播放录音
    play = () => {
        Sound.setCategory('Playback')
        //this.setState({soundLoaded: true})
        this.voice.play((success) => {
              //设置一个轮询使进度条改变
            if (success) {
                this.props.setPlayState(false)
                clearInterval(this.loop_get_time)
                this.setState({voiceProgress: 0})
            } 
        });
        this.loop_get_time = setInterval(() => {
            this.voice.getCurrentTime((sec) => {
                this.setState({voiceProgress: (sec / this.state.voiceLength)})
            })
        }, 100)
    }

    //回放录音
    playback = () => {
        Sound.setCategory('Playback')
        //this.setState({soundLoaded: true})
        this.playback_voice.play((success) => {
              //设置一个轮询使进度条改变
            if (success) {
                this.props.setPlaybackState(false)
                clearInterval(this.loop_get_time)
                this.setState({voiceProgress: 0})
            } 
        });
        this.loop_get_time = setInterval(() => {
            this.playback_voice.getCurrentTime((sec) => {
                this.setState({voiceProgress: (sec / this.state.voiceLength)})
            })
        }, 100)
    }

    playYoudaoSound = (url) => {
        Sound.setCategory('Playback')
        this.youdao_voice = new Sound(url, '', (error) => {
            if (error) {
                //console.log(error, 'error')
                Toast.show('网络异常')
                return;
            }

            this.youdao_voice.play((success) => {
                //设置一个轮询使进度条改变
              if (success) {
                this.youdao_voice.release()
              } 
          });
        });

    }

    //完成录音后对组件做的事情
    afterRecord = (data,seconds,timeStamp) => {
        const {score_weighting} = this.props.user.settings
        const {user} = this.props.user

        if (score_weighting == {}) {
            Toast.show('无法计算分数，请尝试重新登录')
            return
        }
        //先算分数
        if (data.pron_score >= score_weighting.great) {
            this.state.score = 100
        } else {
            this.state.score = 100 * data.pron_score / score_weighting.great
        }


        let postSentence = {};
        postSentence.audio_url = `https://s3.cn-north-1.amazonaws.com.cn/oraltest/audios/${user.login_name}_${timeStamp}.wav`;
        postSentence.audio_time = seconds();
        postSentence.score = this.state.score;
        postSentence.metrics = JSON.stringify(data);
        saveExerciseData(this.props.sentence.id,postSentence).then((data)=>{console.log('save ExerciseData Success:'+JSON.stringify(data))})

        let _words = []
        //新版接口，多了一层phrases，拆掉
        data.phrases.forEach(e => _words.push(...e.words))

        _words = _words.filter((w) => {
            return w.word != "<SIL>"
        })
        let _sentences = this.props.sentence.content.split(" ")
        let _ibmSentences = []
        _sentences.forEach((s, s_index) => {
            let _word_in_ibm = _words.filter((w, w_index) => {
                return s_index == w_index
            })[0]

            //获取音标数据
            let _phones = []
            if (_word_in_ibm != undefined) {
                _word_in_ibm.syllables.forEach((s) => {
                    s.phones.forEach((p) => {
                        _phones.push(p)
                    })
                })
            }
            
            _ibmSentences.push({
                word: s,
                score: _word_in_ibm == undefined ? null : _word_in_ibm.pron_score,
                phones: _phones
            })
        })

        //console.log('_ibmSentences', _ibmSentences)
        this.setState({
            score: Math.floor(this.state.score),
            ibmSentences: _ibmSentences
            //ibmSentences: data.body.words.slice(1,-1) //去除第一个和最后一个
        })

    }


    //根据你状态判断是否可点击
    pendingOnPress = () => {
        const {isPlaying, onPress, sentence, setPlayState, isRecording, isPlaybacking} = this.props
        if (isPlaying || isRecording || isPlaybacking) {
            alert('正在录音中或者正在播放')
            return
        } else {
            //this.setState({soundLoaded: false})
            setPlayState(false)
            onPress(sentence.id)
        }
    }

    render () {
        const {isActive, sentence} = this.props
        return (
            <TouchableOpacity onPress={this.pendingOnPress}>
                <View>
                    {this.youdaoModalTemplate()}
                    {isActive ? this.templateWithActive(sentence) : this.templateWithInActive(sentence)}
                </View>
            </TouchableOpacity>
        )
    }
}

const mapStateToProps = (state) => {
    return {
       user: state.user
    }
}

export default connect(mapStateToProps)(SentenceLabel)